package com.star.controller;

import com.star.config.ThreadPoolConfig;
import com.star.entity.Message;
import com.star.entity.User;
import com.star.service.MessageService;
import com.star.util.JavaMailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;


/**
 * @Description: 留言页面控制器
 * @Date: Created in 10:57 2020/4/16
 * @Author: ONESTAR
 * @QQ群: 530311074
 * @URL: https://onestar.newstar.net.cn/
 */
@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    ThreadPoolConfig threadPoolConfig;

    @Autowired
    JavaMailUtil javaMailUtil;

    @Value("${message.avatar}")
    private String avatar;
    @Value("${spring.mail.username}")
    private String to;

    @GetMapping("/message")
    public String message() {
        return "message";
    }

//    查询留言
    @GetMapping("/messagecomment")
    public String messages(Model model) {
        List<Message> messages = messageService.listMessage();
        model.addAttribute("messages", messages);
        return "message::messageList";
    }

//    新增留言
    @PostMapping("/message")
    public String post(Message message, HttpSession session) {
        User user = (User) session.getAttribute("user");
        //设置头像
        if (user != null) {
            message.setAvatar(user.getAvatar());
            message.setAdminMessage(true);
        } else {
            message.setAvatar(avatar);
        }
        if (message.getParentMessage().getId() != null) {
            message.setParentMessageId(message.getParentMessage().getId());
            message.setParentMessage(messageService.findByParantId(message.getParentMessage().getId()));
        }
        messageService.saveMessage(message);

        //发送邮件
        String toPerson;
        //如果没有父id，则发给管理员
        if (message.getParentMessage() == null){
            toPerson  = to;
        }else{
            toPerson = message.getParentMessage().getEmail();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String content = "<h3>你好！</h3> " +
                "<p>你在Kuang_lib的博客上的留言，有小伙伴回复了。</p>" +
                "<p> 回复时间："+ formatter.format(message.getCreateTime()) +"</p>"+
                "<p> 若想查看回复详细内容请前往<a href='https://www.kuangyuanbin.cn' target='_blank' style='text-decoration: none;color: blue;'>Kuang_lib的博客</a></p>"+
                "<p style='margin-left: 200px;color: red;'>博主：<span>kuang_lib</span></p>";
        threadPoolConfig.threadPoolTaskExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try{
                    javaMailUtil.sendHtmlMail(toPerson,"【Kuang_lib’s 留言板】",content);
//                    System.out.println("邮件发送成功");
                }catch (Exception e){
//                    System.out.println("邮件发送异常");
                    e.printStackTrace();
                }

            }
        });
        return "redirect:/messagecomment";
    }

//    删除留言
    @GetMapping("/messages/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes, Model model){
        messageService.deleteMessage(id);
        return "redirect:/message";
    }

}